import samples.renderer as renderer
import numpy as np
import taichi as ti
from pyrender import build

ti.init(arch=ti.cpu)

N:int = 0
#box = build.build_quad(5,5)
#box = build.build_box(5,5,10)
box = build.build_sphere(6,40,20)
mesh_vec3 = ti.Vector.field(3,dtype=ti.f32,shape=box['points'].shape[0])
mesh_indices = ti.Vector.field(1,dtype=ti.u32,shape=box['trangles'].shape[0]*3)

@ti.kernel
def init_points_pos(pts : ti.types.ndarray(),trs : ti.types.ndarray())->int:
    m = 0
    for i in range(pts.shape[0]):
        mesh_vec3[i] = (pts[i,0],pts[i,1],pts[i,2])
    
    ti.loop_config(serialize=True)
    for i in range(trs.shape[0]):
        a = trs[i,0]
        b = trs[i,1]
        c = trs[i,2]
        n = ti.math.cross(mesh_vec3[b]-mesh_vec3[a],mesh_vec3[c]-mesh_vec3[a])
        if n.z > 0:
            mesh_indices[m][0] = a
            mesh_indices[m+1][0] = b
            mesh_indices[m+2][0] = c
            m = m + 3
            #print(m)
    return m

N = init_points_pos(box['points'],box['trangles'])
print(N)
window = ti.ui.Window("Test for Drawing 3d-lines", (768, 768))
canvas = window.get_canvas()
scene = ti.ui.Scene()
camera = ti.ui.Camera()
camera.position(0, 0, -30)

while window.running:
    camera.track_user_inputs(window, movement_speed=0.03, hold_key=ti.ui.RMB)
    scene.set_camera(camera)
    scene.ambient_light((0.8, 0.8, 0.8))
    scene.point_light(pos=(5, 15, -20), color=(1, 1, 1))

    #scene.particles(particles_pos, color = (0.68, 0.26, 0.19), radius = 0.1)
    # Draw 3d-lines in the scene
    #scene.lines(box_lines, color = (0.28, 0.68, 0.99), width = 2.0)
    scene.mesh(mesh_vec3,mesh_indices,vertex_count=N,show_wireframe=True)
    canvas.scene(scene)
    window.show()
